package com.example.shardingjdbctest.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.FixedValue;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author：kangxuan
 * @date：2024/10/17 4:31 PM
 * @desc: 引入 mybatis-plus-boot-starter 后，在项目启动时，
 * 会获取DataSource对象，创建了 DataSource 也会去校验数据库连接是否可用，校验通过才会正常启动
 */
@Configuration
public class ProjectConfig {
    /**
     * 配置数据源
     * @return
     */
    @Bean
    public DataSource dataSource() {


        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("jdbc:mysql://192.168.56.12:3306/test?useUnicode=true&characterEncoding=UTF-8");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("Rjtx@1234");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        DruidDataSource druidDataSource1 = new DruidDataSource();
        druidDataSource1.setUrl("jdbc:mysql://192.168.56.12:3306/test1?useUnicode=true&characterEncoding=UTF-8");
        druidDataSource1.setUsername("root");
        druidDataSource1.setPassword("Rjtx@1234");
        druidDataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");


        Map<String,DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("ds0",druidDataSource);
        dataSourceMap.put("ds1",druidDataSource1);

        // 创建Enhancer对象
        Enhancer enhancer = new Enhancer();
        // 设置Enhancer的超类（被代理类）
        enhancer.setSuperclass(MyDataSource.class);
        // 设置回调，这里使用FixedValue作为回调，它总是返回一个固定值
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return methodProxy.invokeSuper(obj, args);
            }
        });

        // 创建代理对象
        MyDataSource proxy = (MyDataSource) enhancer.create();
        proxy.setDataSourceMap(dataSourceMap);

        return proxy;
    }
}
